﻿package com.zzvcom.webapp.filter;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionValidFilter implements Filter
{
    private String reURL;//重定URL
    private String  validParam;
    public String getReURL()
    {
        return reURL;
    }

    public void setReURL(String reURL)
    {
        this.reURL = reURL;
    }

    public void destroy()
    {
         
    }

    public void doFilter(ServletRequest servletRequest,
            ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException
    {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        if(validParam.equals("none"))
        {
            filterChain.doFilter(request, response);
            return;
        }
        Object mlist=request.getSession().getAttribute(validParam);
        if(mlist==null)
        {
        	response.sendRedirect(request.getContextPath()+reURL);
            return;
        }
        
        if(mlist instanceof Collection)
        {
            if(((Collection)mlist).size()==0)
            {
                response.sendRedirect(request.getContextPath()+reURL);
                return;
            }
        }
        
        filterChain.doFilter(request, response);
        
        
    }

    public void init(FilterConfig config) throws ServletException
    {
        reURL=config.getInitParameter("reurl");
        validParam=config.getInitParameter("validparam");
        //System.out.println("validparam:"+validParam);
    }

    public String getValidParam()
    {
        return validParam;
    }

    public void setValidParam(String validParam)
    {
        this.validParam = validParam;
    }
}